﻿using System;
using System.Collections.Generic;
using System.Linq;
using Core.Log;
using UnityEditor;
using UnityEngine;
using Util;
using Object = UnityEngine.Object;

namespace Core
{
    /// <summary>
    /// 资源管理器，通过Resources文件夹管理资源
    /// </summary>
    public class ResourceMgr : Singleton<ResourceMgr>
    {
        public const string DATA_PATH = "Data/";
        public const string PREFAB_PATH = "Prefab/";

        public Dictionary<string,Object> mLoadedAssets;

        protected override void OnCreate()
        {
            mLoadedAssets = new Dictionary<string, Object>();
        }

        public T LoadResource<T> (string name) where T :Object
        {
            if (mLoadedAssets.ContainsKey(name) && mLoadedAssets[name] != null)
            {
                return mLoadedAssets[name] as T;
            }
            try
            {
                T asset = Resources.Load<T>(name);
                mLoadedAssets.Add(name, asset);
                return asset;
            } catch (Exception exception)
            {
                ADbg.LogE("[Resource] 资源{0}加载失败，资源不存在");
                return null;
            }
        }
        
        public T LoadData<T>(string name) where T : Object
        {
            return LoadResource<T>(DATA_PATH + name);
        }

        public GameObject LoadPrefab(string name)
        {
            return LoadResource<GameObject>(PREFAB_PATH + name);
        }

        public void UnLoad(Object asset)
        {
            Resources.UnloadAsset(asset);
        }
    }
}